package com.radar.task.tf;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.radar.algorithm.MathCommon;
import com.radar.common.DateConstants;
import com.radar.common.ProductType;
import com.radar.io.CinradRadar;
import com.radar.io.RadarGridData;
import com.radar.task.cd.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import ucar.ma2.DataType;
import ucar.nc2.Attribute;
import ucar.nc2.Group;
import ucar.nc2.Variable;

import java.io.File;
import java.util.Arrays;
import java.util.Date;

/**
 * @author: fy-wbj
 * @description: radar task
 * @date: 2021-04-21
 */

@Component
@Slf4j
public class CappiTFRunnable implements Runnable {

    /**
     * 覆盖代码注释
     * @param file
     */
    public void jobItemRun(File file) {
        String station = file.getName().split("_")[3];
        String date = file.getName().split("_")[4];
        Date dt = DateUtil.parse(date, DateConstants.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        log.info("start parse file : {} , station : {}, date: {}", file.getAbsolutePath(), station, date);
        CinradRadar cinradRadar = new CinradRadar();
        long time = System.currentTimeMillis();
        // out dir
        String outDir = Constants.tmpPath +
                File.separator +
                DateUtil.format(dt, DateConstants.DATE_FORMAT_YYYYMMDD) +
                File.separator +
                station +
                File.separator;
        FileUtil.mkdir(outDir);
        String ncFile = outDir +
                DateUtil.format(dt, DateConstants.DATE_FORMAT_YYYYMMDDHHMM) + ".nc";
        try {
            // set nc File
            cinradRadar.setNetcdfFile(ncFile);
            cinradRadar.parse(file.getAbsolutePath());
            cinradRadar.radar.setProjectStep(0.05);
            RadarGridData data = cinradRadar.radar.getCR();

            double[] alt = new double[]{500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000, 10500, 11000, 11500, 12000};
            double[] xarray = (double[]) cinradRadar.radar.netcdf.findVariable("Longitude_" + ProductType.REF.name()).read().copyToNDJavaArray();
            double[] yarray = (double[]) cinradRadar.radar.netcdf.findVariable("Latitude_" + ProductType.REF.name()).read().copyToNDJavaArray();
            log.info("cr s : {}", System.currentTimeMillis() - time);
            byte[][][] cappi = cinradRadar.radar.cappiTest(ProductType.REF, alt, xarray, yarray);
            log.info("cappi s : {}", System.currentTimeMillis() - time);
            writeCappi(cinradRadar, cappi, alt);
            cinradRadar.radar.flush();
        } catch (Exception e) {
            log.error("start error parse file : {} , station : {}, date: {}", file.getAbsolutePath(), station, date);
            if (cinradRadar.radar != null) {
                cinradRadar.radar.dispose();
            }
            e.printStackTrace();
        }
        log.info("start parse end time : {} ,residue: {},file : {} , station : {}, date: {}", (System.currentTimeMillis() - time) / 1000.0, Constants.singleQueue.size(), file.getAbsolutePath(), station, date);
    }

    /**
     * 覆盖代码注释
     * @param cinradRadar
     * @param cappi
     * @param altArray
     */
    public void writeCappi(CinradRadar cinradRadar, byte[][][] cappi, double[] altArray) {
        cinradRadar.radar.write.addDimension((Group) null, "Altitude", altArray.length);
        Variable v1 = cinradRadar.radar.write.addVariable((Group) null, "Altitude", DataType.DOUBLE, "Altitude");
        v1.addAttribute(new Attribute("units", "m"));
        v1.addAttribute(new Attribute("actual_range", Arrays.asList(altArray[0], altArray[altArray.length - 1])));
        v1.setCachedData(MathCommon.toArray(altArray));
        Variable variable = cinradRadar.radar.write.addVariable((Group) null, "CAPPI", DataType.BYTE, Arrays.asList(
                cinradRadar.radar.netcdf.findDimension("Altitude"),
                cinradRadar.radar.netcdf.findDimension("Latitude_" + ProductType.REF.name()),
                cinradRadar.radar.netcdf.findDimension("Longitude_" + ProductType.REF.name())));
        variable.addAttribute(new Attribute("missing_value", -999.0F));
        variable.addAttribute(new Attribute("full_name", ProductType.CR.getFullName() + "_CAPPI"));
        variable.addAttribute(new Attribute("units", ProductType.CR.getUnit()));
        variable.setCachedData(MathCommon.toByteArray(cappi));
    }

    @Override
    /**
     * 覆盖代码注释
     */
    public void run() {
        while (true) {
            try {
                if (!Constants.singleQueue.isEmpty()) {
                    File poll = Constants.singleQueue.poll();
                    if (poll.exists()) {
                        jobItemRun(poll);
                    }
                } else {
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error(e.getMessage() + "cd item 解析异常出现异常！");
                e.printStackTrace();
            }
        }

    }

    /**
     * 覆盖代码注释
     * @param args
     */
    public static void main(String[] args) {
        new CappiTFRunnable().jobItemRun(new File("E:\\data\\radar/radardata/Z9090/Z_RADR_I_Z9090_20210716015513_O_DOR_SB_CAP_FMT.bin"));
    }
}
